const app = getApp();
const {
  $resHost
} = app.globalData;
const defaultPng = `${$resHost}/img/def.jpg`;
Component({
  properties: {
    isNew: {
      type: Boolean,
      value: false
    }
  },
  data: {
    navList: [],
    navIndex: 0
  },
  lifetimes: {
    attached() {
      this.getClassList();
    }
  },
  methods: {
    onSearch(e) {
      let url = `/pages/TabBar/Goods/new?type=1&searchName=${e.detail.value}`;
      xhs.navigateTo({
        url
      });
    },
    changeNavId({
      currentTarget: {
        dataset: {
          index
        }
      }
    }) {
      if (index !== this.data.navIndex) {
        this.setData({
          navIndex: +index
        });
      }
    },
    getClassList() {
      /**
      * @api 展示类目列表
      * @param int status 状态[-1=全部][0=隐藏][1=展示]
      */

      app.$getSuccessData('/user/goods/show-class-list', {
        status: 1
      }).then(navList => {
        this.setData({
          navList: this.initData(navList)
        });
      });
    },
    async goGoods(e) {
      let {
          id,
          item
        } = e.currentTarget.dataset,
        url = '';
      if (item.mapType == '3') {
        url = item.mapContent;
      } else if (item.mapType == '1') {
        url = `/pages/TabBar/Goods/new?type=1&searchName=${item.mapContent}`;
      } else {
        try {
          const data = await app.$getSuccessData("/user/goods/get-class-id", {
            id
          });
          url = `/pages/TabBar/Goods/new?classId=${data}`;
        } catch (error) {
          console.error("获取 classId 对应的 URL 失败:", error);
          url = "";
        }
      }
      xhs.navigateTo({
        url,
        fail: function (res) {
          xhs.switchTab({
            url
          }), console.log(res);
        }
      });
    },
    initData(list, deep = 1) {
      const result = [];
      list.forEach(item => {
        let obj = {};
        if (deep !== 3) {
          item.child = this.initData(item.child, deep + 1);
          //if (!item.child.length) return
          obj = {
            id: item.id,
            className: item.name.slice(0, 6),
            iconUrl: item.iconUrl.url || defaultPng,
            child: item.child,
            mapType: item.mapType,
            mapContent: item.mapContent
          };
        } else {
          obj = {
            id: item.id,
            className: item.name.slice(0, 6),
            iconUrl: item.iconUrl.url || defaultPng,
            mapType: item.mapType,
            mapContent: item.mapContent
          };
        }
        result.push(obj);
      });
      return result;
    }
  }
});